package leesoft.gocrm.models.handler;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import leesoft.gocrm.models.Contact;
import leesoft.gocrm.models.interfaces.ISearchContact;
import leesoft.gocrm.utils.GDataUtils;
import leesoft.gocrm.utils.PropertyManager;
import leesoft.gocrm.utils.TextUtils;

import com.google.gdata.client.Query.CustomParameter;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.ContactGroupEntry;
import com.google.gdata.data.contacts.ContactGroupFeed;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.client.Query;

public class SearchContact implements ISearchContact {

	public List<Contact> searchContactByKeyword(String keyword) {
		// TODO Auto-generated method stub
		ContactsService service=new ContactsService("cn-com-leesoft-gocrm");
		ArrayList<Contact> results=new ArrayList<Contact>();
		try{
			service.setUserCredentials(PropertyManager.getInstance().getGContactApiUserName(),
				PropertyManager.getInstance().getGContactApiPassword());
			//Logger.global.log(Level.FINEST,"username/password:"+PropertyManager.getInstance().getGContactApiUserName()+"/"+PropertyManager.getInstance().getGContactApiPassword());
			URL feedURL;
			//First Get availabe group id
			feedURL=new URL("http://www.google.com/m8/feeds/groups/"+getApiUserName()+"/full");
			Logger.global.log(Level.FINE,"group feed url:"+feedURL.toString());
			ContactGroupFeed resultFeed=service.getFeed(feedURL, ContactGroupFeed.class);
			ArrayList<String> availableGroup=new ArrayList<String>();
			for(ContactGroupEntry entry:resultFeed.getEntries())
			{
				if(isAailableGroup(entry.getTitle().getPlainText()))
				{
					Logger.global.log(Level.FINE,"Group with id:"+entry.getId()+" is available");
					availableGroup.add(entry.getId());
				}
			}
			feedURL=new URL("http://www.google.com/m8/feeds/contacts/"+getApiUserName()+"/full");
			for(String groupId:availableGroup)
			{
				Query query=new Query(feedURL);
				query.setStringCustomParameter("group", groupId);
				ContactFeed contactsFeed=service.query(query, ContactFeed.class);
				
				for(ContactEntry entry:contactsFeed.getEntries())
				{
					Contact contact=new Contact(entry.getContactPhotoLink().getHref(),getPrintableName(entry.getName()),entry.getId());
					if(contact.getName().toLowerCase().indexOf(keyword.toLowerCase())>=0)
					{
						results.add(contact);
						Logger.global.log(Level.FINE,"contact ["+contact.getName()+"] added");
					}
				}
			}
		}catch(AuthenticationException e)
		{
			Logger.global.log(Level.SEVERE, "Authenticate failed, please either contact the support team or check your gocrm.property file");
		}catch(Exception e)
		{
			Logger.global.log(Level.SEVERE,"Fatal when try to loading data from google contact: "+e.getMessage());
			StringWriter writer=new StringWriter();
			e.printStackTrace(new PrintWriter(writer));
			Logger.global.log(Level.FINE,writer.toString());
		}
		return results;
	}
	private boolean isAailableGroup(String groupName)
	{
		for(String group:PropertyManager.getInstance().getGDataContactsGroups())
		{
			if(group.equals(groupName))
				return true;
		}
		return false;
	}
	private String getApiUserName()
	{
		return PropertyManager.getInstance().getGContactApiUserName();
	}
	private String getPrintableName(Name name)
	{
		return GDataUtils.safeGetGivenName(name.getGivenName())+" "+GDataUtils.safeGetFamilyName(name.getFamilyName());
	}

}
